package com.shensi.adminCollect.utils.system;


import com.alibaba.fastjson.JSONException;
import com.alibaba.fastjson.JSONObject;
import com.shensi.adminCollect.common.exception.CustomException;
import com.shensi.adminCollect.common.utils.StringUtils;
import com.shensi.adminCollect.domain.system.HttpRequestUtil;
import com.shensi.adminCollect.domain.system.Token;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;

/**
 * <Title>工具类: WeiXinUtil</Title>
 */
public class WxUserUtil {
    //凭证获取路径
    public final static String TOKEN_URL = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=%s&secret=%s";

    // 获取生成带参数的二维码ticket
    private static final String WX_QR_CODE = "https://api.weixin.qq.com/cgi-bin/qrcode/create?access_token=%s";

    // 获取生成带参数的二维码
    private static final String WX_QR_CODE_URL = "https://mp.weixin.qq.com/cgi-bin/showqrcode?ticket=%s";
    //日志
    private static final Logger logger = LoggerFactory.getLogger(WxUserUtil.class);

    /*
     * 获取接口访问凭证
     * @param appId         //凭证
     * @param appSecret     //密钥
     * @return
     */
    public static Token getToken(String appId, String appSecret) {
        Token token = null;
        String requestUrl = String.format(TOKEN_URL, appId, appSecret);
        //发起GET请求获取凭证
        logger.info("weixin getToken req : " + requestUrl);
        JSONObject jsonObject = HttpRequestUtil.getHttpsRequestData(requestUrl, "GET", null);
        logger.info("weixin getToken res : " + JSONObject.toJSONString(jsonObject));
        if (jsonObject != null) {
            try {
                token = new Token();
                token.setAccessToken(jsonObject.getString("access_token"));
                token.setExpiresIn(jsonObject.getInteger("expires_in"));
            } catch (JSONException e) {
                e.printStackTrace();
            }
        }
        return token;
    }

    /**
     * 获取公众号动态二维码
     *
     * @param token  授权token
     * @param key    场景值（标识）
     * @param type   二维码时效 false 临时 true 永久
     * @param expire 时效
     * @return
     */
    public static String getQrcode(String token, String key, boolean type, Long expire) {
        String url = String.format(WX_QR_CODE, token);
        JSONObject scene = new JSONObject();
        scene.put("scene_str", key);
        JSONObject actionInfo = new JSONObject();
        actionInfo.put("scene", scene);
        JSONObject req = new JSONObject();

        // QR_LIMIT_STR_SCENE(永久)  QR_STR_SCENE （临时）
        if (type) {
            req.put("action_name", "QR_LIMIT_STR_SCENE");
        } else {
            req.put("action_name", "QR_STR_SCENE");
            req.put("expire_seconds", expire);
        }
        req.put("action_info", actionInfo);
        String data = JSONObject.toJSONString(req);
        //发送post请求
        logger.info("weixin getQrcode url : " + url);
        logger.info("weixin getQrcode req : " + JSONObject.toJSONString(data));
        JSONObject jsonObject = HttpRequestUtil.getHttpsRequestData(url, "POST", data);
        logger.info("weixin getQrcode res : " + JSONObject.toJSONString(jsonObject));

        if (null != jsonObject) {
            String ticket = jsonObject.getString("ticket");
            if (StringUtils.isBlank(ticket)) {
                throw new CustomException("获取微信生成二维码ticket为null！");
            }
            try {
                return String.format(WX_QR_CODE_URL, URLEncoder.encode(ticket, "UTF-8"));
            } catch (UnsupportedEncodingException e) {
                logger.error(e.getMessage());
            }
        }
        // 二维码：https://mp.weixin.qq.com/cgi-bin/showqrcode?ticket=gQGE8DwAAAAAAAAAAS5odHRwOi8vd2VpeGluLnFxLmNvbS9xLzAyam80X3dYRDVkb0gxNjZxaDFBYzYAAgQGIAhkAwSAOgkA
        return null;
    }
}
